function [dist,dist_closest,med_dist_no,...
    frac_above_prclow,frac_above_med_dist_no,frac_above_prchigh] = get_dist(t,comm_loc,distance)
    % dist and dist_closest
    locnew=find(comm_loc(:,t-1)==0 & comm_loc(:,t)==1); % new branch
    locexist=find(comm_loc(:,t-1)==1); % exist branch
    locno=find(comm_loc(:,t-1)==0); % no branch

    [dist,closest_exist]=min(distance(locexist,locnew));
    closest_exist=locexist(closest_exist);
    
    index_invalid=find(dist==1.5e6);
    dist(index_invalid)=[];
    locnew(index_invalid)=[];
    closest_exist(index_invalid)=[];
    



    [dist_closest,loc_closest]=min(distance(locno,locexist));
    [~,id]=sort(dist_closest,'ascend');
    dist_closest=dist_closest(id); loc_closest=loc_closest(id);
    dist_closest=dist_closest(1:length(locnew)); loc_closest=loc_closest(1:length(locnew));
    


    
    dist=dist';
    dist_closest=dist_closest';

    % med_dist_no, calculates the median car travel time to the nearest branch of markets without branches in each year
    locyes=find(comm_loc(:,t)==1);
    locno=find(comm_loc(:,t)==0);
    med_dist_no=median(min(distance(locyes,locno)));

    prclow=prctile(min(distance(locyes,locno)),25);
    prchigh=prctile(min(distance(locyes,locno)),75);

    n_invalid=length(index_invalid);
    n=length(dist)+n_invalid;
    frac_above_prclow=(sum(dist>prclow)+n_invalid)/n;
    frac_above_med_dist_no=(sum(dist>med_dist_no)+n_invalid)/n;
    frac_above_prchigh=(sum(dist>prchigh)+n_invalid)/n;
end